//
//  LiveViewController.swift
//  DHLive
//
//  Created by Mac on 2021/7/20.
//

import UIKit

let IJKMPMoviePlayerLoadStateDidChangeNotification = "IJKMPMoviePlayerLoadStateDidChangeNotification"

let IJKMPMoviePlayerPlaybackDidFinishNotification = "IJKMPMoviePlayerPlaybackDidFinishNotification"

let IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification = "IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification"

let IJKMPMoviePlayerPlaybackStateDidChangeNotification = "IJKMPMoviePlayerPlaybackStateDidChangeNotification"

class LiveViewController: BaseViewController {
    var streamAddr: String = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/bipbop_4x3_variant.m3u8"
    var player: IJKMediaPlayback? = nil
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .randomColor
        #if DEBUG
        IJKFFMoviePlayerController.setLogReport(true)
        IJKFFMoviePlayerController.setLogLevel(k_IJK_LOG_DEBUG)
        #else
        IJKFFMoviePlayerController.setLogReport(false)
        IJKFFMoviePlayerController.setLogLevel(k_IJK_LOG_INFO)
        #endif
        
        IJKFFMoviePlayerController.checkIfFFmpegVersionMatch(true)

        let options = IJKFFOptions.byDefault()
        player = IJKFFMoviePlayerController(contentURL: URL(string: streamAddr)!, with: options)
        
        player?.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        player?.view.frame = view.bounds
        player?.scalingMode = .aspectFit
        player?.shouldAutoplay = true
        
        view.autoresizesSubviews = true
        view.addSubview((player?.view)!)
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        installMovieNotificationObservers()
        player?.prepareToPlay()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        player?.shutdown()
        removeMovieNotificationObservers()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        player?.play()
    }
    
}

//MARK: - 注册通知
extension LiveViewController {
    func installMovieNotificationObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(loadStateDidChange(noti:)), name: NSNotification.Name(rawValue: IJKMPMoviePlayerLoadStateDidChangeNotification), object: player)
        NotificationCenter.default.addObserver(self, selector: #selector(moviePlayBackDidFinish(noti:)), name: NSNotification.Name(rawValue: IJKMPMoviePlayerPlaybackDidFinishNotification), object: player)

        NotificationCenter.default.addObserver(self, selector: #selector(mediaIsPreparedToPlayDidChange(noti:)), name: NSNotification.Name(rawValue: IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification), object: player)

        NotificationCenter.default.addObserver(self, selector: #selector(moviePlayBackStateDidChange(noti:)), name: NSNotification.Name(rawValue: IJKMPMoviePlayerPlaybackStateDidChangeNotification), object: player)
    }
}

//MARK: - 移除通知
extension LiveViewController {
    func removeMovieNotificationObservers() {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: IJKMPMoviePlayerLoadStateDidChangeNotification), object: player)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: IJKMPMoviePlayerPlaybackDidFinishNotification), object: player)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: IJKMPMediaPlaybackIsPreparedToPlayDidChangeNotification), object: player)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: IJKMPMoviePlayerPlaybackStateDidChangeNotification), object: player)
    }
}


extension LiveViewController {
    @objc func loadStateDidChange(noti: Notification) {
        let loadState = player?.loadState
        if (loadState!.rawValue & IJKMPMovieLoadState.playthroughOK.rawValue) != 0 {
            print("loadStateDidChange: IJKMPMovieLoadStatePlaythroughOK:\(loadState!)")
        }else if (loadState!.rawValue & IJKMPMovieLoadState.stalled.rawValue) != 0 {
            print("loadStateDidChange: IJKMPMovieLoadStateStalled:\(loadState!)")
        }else {
            print("loadStateDidChange: ???:\(loadState!)")
        }
    }
    
    @objc func moviePlayBackDidFinish(noti: Notification) {
        let reason = noti.userInfo?[IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey] as? IJKMPMovieFinishReason
        switch reason {
        case .playbackEnded:
            print("playbackStateDidChange: IJKMPMovieFinishReasonPlaybackEnded:\(reason!)")
            
        case .userExited:
            print("playbackStateDidChange: IJKMPMovieFinishReasonUserExited: \(reason!)")
            
        case .playbackError:
            print("playbackStateDidChange: IJKMPMovieFinishReasonPlaybackError: \(reason!)")
            
        default:
            print("playbackPlayBackDidFinish: ???: \(reason as Any)")
        }
    }
    @objc func mediaIsPreparedToPlayDidChange(noti: Notification) {
        print(#function)
    }
    @objc func moviePlayBackStateDidChange(noti: Notification) {
        switch player?.playbackState {
        case .stopped:
            print("IJKMPMoviePlayBackStateDidChange \(player?.playbackState as Any): stoped")
        case .playing:
            print("IJKMPMoviePlayBackStateDidChange \(player?.playbackState as Any): playing")
        case .paused:
            print("IJKMPMoviePlayBackStateDidChange \(player?.playbackState as Any): paused")
        case .interrupted:
            print("IJKMPMoviePlayBackStateDidChange \(player?.playbackState as Any): interrupted")
        case .seekingBackward, .seekingForward:
            print("IJKMPMoviePlayBackStateDidChange \(player?.playbackState as Any): seeking")
        default:
            print("IJKMPMoviePlayBackStateDidChange \(player?.playbackState as Any): unknown")
        }
    }
}
